package com.test.study.jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Logger;

public class C3P0Demo1 {
    private final static Logger log = Logger.getLogger(C3P0Demo1.class.getName());

    @Test
    public void c3p0Demo() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/mp?characterEncoding=utf8&useUnicode=true&rewriteBatchedStatements=true");
            dataSource.setUser("root");
            dataSource.setPassword("root");
            String sql = "select * from user_test";
            connection=dataSource.getConnection();
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                String nickname = resultSet.getString("nickname");
                int age = resultSet.getInt("age");
                log.info(id + "\t" + username + "\t" + password + "\t" + nickname + "\t" + age);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
            JdbcUtils.close(connection, statement, resultSet);
        }

    }

    @Test
    public void c3p0ConfigDemo() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();//参数可以指定加载那个数据库
            String sql = "select * from user_test";
            connection=dataSource.getConnection();
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                String nickname = resultSet.getString("nickname");
                int age = resultSet.getInt("age");
                log.info(id + "\t" + username + "\t" + password + "\t" + nickname + "\t" + age);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
            JdbcUtils.close(connection, statement, resultSet);
        }

    }
}
